<template>
  <div>
    <h1>分类维护页面</h1>
    <el-switch
      v-model="draggable"
      active-color="#13ce66"
      :active-value="true"
      :inactive-value="false"
      inactive-color="#ff4949"
    >
    </el-switch
    >开启拖拽
    <!-- <el-tree :data="data"  node-key="catId" :props="defaultProps" :draggable="draggable" 
    :expand-on-click-node="false" :allow-drop="allowDrop"  :default-expanded-keys="defaulteExpandedKeys"
       @node-drop="nodeDrop">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button type="text" size="mini" @click="() => append(data)">
            Append
          </el-button>
          <el-button type="text" size="mini" @click="() => update(data)">
            Update
          </el-button>
          <el-button
            type="text"
            v-if="node.childNodes.length == 0"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree> -->
    
    <el-tree
      node-key="catId"
      :data="data"
      :props="defaultProps"
      :draggable="draggable"
      :allow-drop="allowDrop"
      :default-expanded-keys="defaulteExpandedKeys"
      :expand-on-click-node="false"
      @node-drop="nodeDrop"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button type="text" size="mini" @click="() => append(data)">
            Append
          </el-button>
          <el-button type="text" size="mini" @click="() => update(data)">
            update
          </el-button>
          <el-button
            type="text"
            v-if="node.childNodes.length == 0"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>

    <!-- 添加彈窗 -->
    <el-dialog title="三级分类" :visible.sync="dialogFormVisible">
      <el-form :model="category">
        {{ category }}
        <el-form-item label="活动名称" label-width="formLabelWidth">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      draggable: false, //可拖拽结点功能
      defaulteExpandedKeys: [],
      formLabelWidth: "120px",
      dialogFormVisible: false,
      category: { catId: "", parentCid: "", catLevel: "", sort: "", name: "" },
      data: [],
      defaultProps: {
        children: "children",
        label: "name", // 要修改成name
      },
      countLeve: 0,
      pid: 0, //父类的id
      updateNodes: [], //收集元素的集合
      catLevel: 0, //等级
    };
  },
  methods: {
    //列表的展示
    getTreeList() {
      this.$http({
        url: this.$http.adornUrl(`/produce/category/tree/list`),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        console.log(data);
        this.data = data.list;
      });
    },
    //做增删改查的方法
    //增加的时候的弹框
    append(node){
      //弹框弹出
      this.dialogFormVisible=true;
      //fid等于node的id
      this.category.parentCid=node.catId;
      //等级是下一级
      this.category.catLevel=node.catLevel+1;
      //排序默认为0
      this.category.sort=0;
    },
    //修改的时候的回显
    update(node){
        //弹框弹出
      this.dialogFormVisible=true;
      //根据id去查询
       this.$http({
        url: this.$http.adornUrl(`/produce/category/info/${node.catId}`),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        console.log(data);
        this.category = data.category;
      });
    },
    //增  或者修改
    save() {
      let baseUrl="save";
      if(this.category.catId){
          baseUrl="update"
      }
   
       
          this.$http({
            url: this.$http.adornUrl(
              `/produce/category/${baseUrl}`
            ),
            method: "post",
            data: this.$http.adornData(
              this.category,false
            ),
          }).then(({ data }) => {
           
            if (data && data.code === 0) {
               console.log("ssss",data);
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
              //弹框消失
              this.dialogFormVisible =false;
              //刷新
              this.getTreeList();
              //成功之后默认展开列表
              this.defaulteExpandedKeys[0]=this.category.parentCid;
              //数据清空
              this.category={};
            } else {
              this.$message.error(data.msg);
            }
          });
       
     
    },

    //进行删除
        remove(node, data) {
          this.$confirm(`确定对[id=${data.catId}]进行[删除]操作?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              //后台接收的是一个数组 所以定义一个数组 数组存放的就是要删除的数据
              var ids = [data.catId];
              //defaulteExpandedKeys 默认展开的节点的 key 的数组
              //删除之后要默认展开当前删除的对象的父id
              this.defaulteExpandedKeys[0] = data.parentCid;
              this.$http({
                url: this.$http.adornUrl(`/produce/category/delete`),
                method: "post",
                //将刚定义好的变量进行传值，给一个默认值
                data: this.$http.adornData(ids, false),
              }).then(({ data }) => {
                if (data && data.code === 0) {
                  this.$message({
                    message: "操作成功",
                    type: "success",
                    duration: 1500,
                    onClose: () => {
                      //删除成功  刷新页面
                      this.getTreeList();
                    },
                  });
                } else {
                  this.$message.error(data.msg);
                }
              });
            })
            .catch(() => {});
        },
  
      //拖拽
      allowDrop(draggingNode, dropNode, type){
        console.log(draggingNode, dropNode, type);
        this.getlevel(draggingNode);
        if(type=="next" || type=="pre"){
          if(this.countLeve==3 && dropNode.data.catLevel == 1) return true;
          if(this.countLeve==2 && dropNode.data.catLevel!=3) return true;
          if(this.countLeve==1) return true;
        }else{
          //里面的
          if(this.countLeve==2 && dropNode.data.catLevel==1) return true;
          if(this.countLeve==1 && dropNode.data.catLevel!=3)return true;
        }

        //默认是false  不能拖拽
        return false;
      },
      getlevel(node){
          //是一级  
          this.countLeve=1;
          if(node.childNodes.length>0){
            //有二级
            this.countLeve=2;
            for(var i=0 ; i<node.childNodes.length;i++){
              if(node.childNodes[i].childNodes>0){
                this.countLeve=3;
                break;
              }
            }
          }

      },
    //执行方法：
    //第一个参数 ：被拖拽对象
    //第二个 ： 目标对象
    //第三个：类型
    nodeDrop(draggingNode, dropNode, type) {
      //根据类型判断
      if (type == "after" || type == "before") {
        //前后拖拽是拖拽对象是目标对象的fid
        this.pid = dropNode.data.parentCid;
        //判断一下等级 此时的等级是目标对象的等级
        this.catLevel = dropNode.data.catLevel;

        //先把目标对象的父元素的子元素数据进行添加
        this.collcation(dropNode.parent.childNodes);
        //调用方法去收集元素   
        //此时判断的条件是 被拖拽对象的的能级和目标对象的等级不同 同时被拖拽的自己不是空
        //所以说现在判断的是二级所有的元素
        if (
          draggingNode.level != dropNode.level &&
          draggingNode.childNodes.length != 0
        ) { //指定了是二级
          //给被拖拽对象的子元素做操作。
          this.pid=draggingNode.data.catId;
          //层级也发生改变  层级是目标对象的层级
          this.catLevel=draggingNode.data.catLevel;
          console.log("此时pid=",this.pid+"等级：",this.catLevel);
          //是把所有被拖拽对象的子元素
          this.collcation(draggingNode.childNodes);
        }
      }
      else {
        //里拖拽
        this.pid = dropNode.data.catId;
        //等级就是目标对象的等级+1
        this.catLevel = dropNode.data.catLevel + 1;
        this.collcation(dropNode.childNodes)
      }
      console.log(draggingNode, dropNode, type)
      console.log(this.updateNodes);
         //给后套发送请求
      this.$http({
        url: this.$http.adornUrl(`/produce/category/updatenode`),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        console.log(data);
        if (data.code == 0) {
          this.$message({
            message: "拖拽成功",
            type: "success",
          });
        }
        console.log(data);
      });
      this.updateNodes = [];

      console.log("目前拖拽的fid是：", this.pid + "等级为：", this.catLevel);
    },

    collcation(nodes) {
      console.log("传过来的是：" + nodes);
      for (var i = 0; i < nodes.length; i++) {

        this.updateNodes.push({
          catId: nodes[i].data.catId,
          name: nodes[i].data.name,
          parentCid: this.pid,
          sort: i,
          catLevel: this.catLevel,
        });
      }
      console.log(this.updateNodes);

    },

  },

  created() {
    this.getTreeList();
  },
};
</script>


